<?php
/*
 * @Description    : 跨域中间件
 * @Version        : 1.0.0
 * @Author         : QianLong
 * @Date           : 2021-03-29 22:47:26
 * @LastEditors    : QianLong
 * @LastEditTime   : 2021-11-04 11:15:09
 */

declare(strict_types=1);

namespace app\middleware;

class Cores
{
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure       $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
        $response = $next($request);
        $origin = $request->header('Origin', '');

        //OPTIONS请求返回204请求
        if ($request->method(true) === 'OPTIONS') {
            $response->code(204);
        }
        $response->header([
            'Access-Control-Allow-Origin'      => $origin,
            'Access-Control-Allow-Methods'     => 'GET,POST,PUT,OPTIONS',
            'Access-Control-Allow-Credentials' => 'true',
            'Access-Control-Allow-Headers'     => '*',
        ]);

        return $response;
    }
}
